<?php

use
    Phalcon\Paginator\Adapter\QueryBuilder as Paginator;

class CustomerController extends ControllerBase
{

    public function initialize()
    {
        parent::initialize();

        $this->view->requireJS = 'customer';
    }

    public function indexAction($status = 0)
    {
        $request = $this->request;
        $user_id = $this->auth->user_id;

        $filter = array_map('trim', array(
            'nickname'        => $request->getQuery('nickname'),
            'type_id'         => $request->getQuery('type_id'),
            'email'           => $request->getQuery('email'),
            'mobile'          => $request->getQuery('mobile'),
            'phone'           => $request->getQuery('phone'),
            'country_id'      => $request->getQuery('country_id'),
            'reg_time_from'   => $request->getQuery('reg_time_from'),
            'reg_time_to'     => $request->getQuery('reg_time_to'),
            'merchant_id'     => $request->getQuery('merchant_id', 'int'),
            'web_uid'         => $request->getQuery('web_uid', 'int'),
            'mt4_demo'        => $request->getQuery('mt4_demo', 'int'),
            'mt4_live'        => $request->getQuery('mt4_live', 'int'),
            'creator'         => $request->getQuery('creator', 'int'),
            'manager_user_id' => $request->getQuery('manager_user_id', 'int'),
            'sales_user_id'   => $request->getQuery('sales_user_id', 'int'),
            'status'          => $request->getQuery('status', null, $status),
            'assigned_to'     => $user_id,
        ));

        $sortColumn = $request->getQuery('col', null, 'reg_time');
        $sortDirect = $request->getQuery('dir', null, 'DESC');

        // 允许排序的字段
        $sortColumns = array(
            'type_id'         => 'Type',
            'email'           => 'Email',
            'nickname'        => 'Nickname',
            'mobile'          => 'Mobile',
            'phone'           => 'Phone',
            'web_uid'         => 'UID',
            'reg_time'        => 'Register At',
            'merchant_id'     => 'IB',
            'mt4_demo'        => 'DEMO',
            'mt4_live'        => 'LIVE',
            'country_id'      => 'Country',
            'last_deposited'  => 'Last Deposited',
            'assign_time'     => 'Assigned Time',
            'creator'         => 'Creator',
            'manager_user_id' => 'Leader',
            'sales_user_id'   => 'Sales',
            'last_followed'   => 'Last Followed',
            'ctime'           => 'Created At',
            'mtime'           => 'Modified At',
        );

        if (! in_array($column, $sortColumns)) {
            $column = 'reg_time';
        }

        if (strtoupper($sortDirect) !== 'ASC') {
            $sortDirect = 'DESC';
        }

        $builder = OaCustomers::getFilterBuilder($filter)->orderBy("$sortColumn $sortDirect");

        $paginator = new Paginator(array(
            'builder' => $builder,
            'limit'   => 20,
            'page'    => $request->getQuery('page', 'int', 1),
        ));

        $subtitle = OaSales::isStaff($user_id) || OaSales::isManager($user_id) ? __('My Customers') : __('All Customers');

        $this->view->subtitle    = $subtitle;
        $this->view->breadcrumbs = array(array('customer/to-be-assigned', $subtitle));
        $this->view->filter      = $filter;
        $this->view->sortColumns = $sortColumns;
        $this->view->sortColumn  = $sortColumn;
        $this->view->sortDirect  = $sortDirect;
        $this->view->page        = $paginator->getPaginate();
        $this->view->types       = OaCustomerTypes::getAll();
        $this->view->countries   = OaCustomers::getUsedCountries();
        $this->view->managers    = OaUserRoles::findUsersByRoles(array(OaRoles::SALES_DIRECTOR, OaRoles::SALES_MANANGER));
        $this->view->sales       = OaUserRoles::findUsersByRoles(OaRoles::SALES_STAFF);
        $this->view->columns     = explode(',', 'nickname,type_id,email,mobile,country_id,reg_time,merchant_id,mt4_demo,mt4_live,web_uid,creator,manager_user_id,sales_user_id');
        $this->view->actions     = array('add', 'import', 'export', 'assign', 'modify', 'follow');
    }

    public function assignedAction()
    {
        $this->indexAction(OaCustomers::ASSIGNED);

        $this->view->subtitle    = __('Assigned');
        $this->view->breadcrumbs = array(array('customer/assigned', __('Assigned')));
        $this->view->columns     = explode(',', 'nickname,type_id,email,mobile,phone,country_id,reg_time,merchant_id,mt4_demo,mt4_live,web_uid,last_followed,creator,manager_user_id,sales_user_id');
        $this->view->actions     = array('assign', 'modify', 'follow');
        $this->view->pick('customer/index');
    }

    public function toBeAssignedAction()
    {
        $this->indexAction(OaCustomers::TO_BE_ASSIGNED);

        $this->view->subtitle    = __('To Be Assigned');
        $this->view->breadcrumbs = array(array('customer/to-be-assigned', __('To Be Assigned')));
        $this->view->columns     = explode(',', 'nickname,type_id,email,mobile,country_id,reg_time,merchant_id,mt4_demo,mt4_live,web_uid,manager_user_id');
        $this->view->actions     = array('assign', 'modify');
        $this->view->pick('customer/index');
    }

    public function noFollowUpAction()
    {
        $this->indexAction(OaCustomers::NO_FOLLOW_UP);

        $this->view->subtitle    = __('No Follow-up');
        $this->view->breadcrumbs = array(array('customer/no-follow-up', __('No Follow-up')));
        $this->view->columns     = explode(',', 'nickname,type_id,email,mobile,country_id,reg_time,merchant_id,mt4_demo,mt4_live,web_uid,manager_user_id,sales_user_id');
        $this->view->actions     = array('assign', 'follow');
        $this->view->pick('customer/index');
    }

    public function assignAction($customer_id)
    {
        $request = $this->request;

        if ($request->isPost() && $request->isAjax()) {
            $customers       = $request->getPost('customers');
            $assign_id       = $request->getPost('assign_id', 'int');
            $manager_user_id = $request->getPost('manager_user_id', 'int');
            $sales_user_id   = $request->getPost('sales_user_id', 'int');

            if (count($customers) === 0) {
                return $this->ajax->error(__('Checked customers is required'));
            }

            if (! $assign_id) {
                return $this->ajax->error(__('Please select aassign batch'));
            }

            if (! $manager_user_id) {
                return $this->ajax->error(__('Please select sales'));
            }

            $nums = 0;
            foreach ($customers as $customer_id) {
                if ($model = OaCustomers::findFirst('customer_id=' . $customer_id)) {
                    $model->assignTo($assign_id, $manager_user_id, $sales_user_id) && $nums++;
                }
            }

            return $nums ?
                $this->ajax->success(__('Assigned total :nums customers', array(':nums' => $nums))) :
                $this->ajax->error(__('Nothing assigned'));
        }

        $conditions = array(
            'order' => 'ctime desc',
            'limit' => 20
        );

        $this->view->customer_id   = $customer_id;
        $this->view->assigns       = OaCustomerAssigns::find($conditions)->toArray();
        $this->view->managers      = OaUserRoles::findUsersByRoles(array(OaRoles::SALES_DIRECTOR, OaRoles::SALES_MANANGER));
        $this->view->sales         = OaUserRoles::findUsersByRoles(OaRoles::SALES_STAFF);
    }

    public function newAssignAction()
    {
        $data = array(
            'description' => $this->request->getPost('name'),
            'creator'     => $this->auth->user_id,
        );

        $model = new OaCustomerAssigns;
        if (! $model->create($data)) {
            return $this->ajax->error($model->getMessage());
        }

        return $this->ajax->success(null, $model->toArray());
    }

    public function modifyAction($customer_id)
    {
        $request     = $this->request;
        $customer_id = (integer) $customer_id;
        $customer    = OaCustomers::findFirst('customer_id=' . $customer_id);
        $details     = OaCustomerDetails::findFirst('customer_id=' . $customer_id);

        if (! $customer) {
            return $this->forward('error/modal', array('message' => 'The record not found'));
        }

        if ($request->isPost()) {
            foreach ($request->getPost() as $key => $value) {
                if (isset($customer->$key)) {
                    if ($key === 'reg_time') {
                        $value = strtotime($value);
                    }

                    $customer->$key = $value;
                } elseif (isset($details->$key)) {
                    $details->$key = $value;
                }
            }

            if (! $customer->update()) {
                return $this->ajax->error(__($customer->getMessage()));
            }

            if (! $details->update()) {
                return $this->ajax->error(__($details->getMessage()));
            }

            return $this->ajax->success(__('Customer information updated succeed'));
        }

        $this->view->customer  = $customer;
        $this->view->details   = $details;
        $this->view->types     = OaCustomerTypes::getAll();
        $this->view->countries = OaCustomers::getUsedCountries();
        $this->view->managers  = OaUserRoles::findUsersByRoles(array(OaRoles::SALES_DIRECTOR, OaRoles::SALES_MANANGER));
        $this->view->sales     = OaUserRoles::findUsersByRoles(OaRoles::SALES_STAFF);
    }

    public function createAction()
    {
        $request = $this->request;

        if ($request->isPost()) {
            $customer = new OaCustomers;
            $details  = new OaCustomerDetails;
            foreach ($request->getPost() as $key => $value) {
                if (isset($customer->$key)) {
                    if ($key === 'reg_time') {
                        $value = strtotime($value);
                    }

                    $customer->$key = $value;
                } elseif (isset($details->$key)) {
                    $details->$key = $value;
                }
            }

            if (! $customer->create()) {
                return $this->ajax->error(__($customer->getMessage()));
            }

            // 获取 id
            $details->customer_id = $customer->customer_id;

            if (! $details->create()) {
                return $this->ajax->error(__($details->getMessage()));
            }

            return $this->ajax->success(__('New customer added completed'));
        }

        $this->view->types     = OaCustomerTypes::getAll();
        $this->view->countries = OaCustomers::getUsedCountries();
        $this->view->managers  = OaUserRoles::findUsersByRoles(array(OaRoles::SALES_DIRECTOR, OaRoles::SALES_MANANGER));
        $this->view->sales     = OaUserRoles::findUsersByRoles(OaRoles::SALES_STAFF);
    }

    public function followAction($customer_id)
    {
        $request     = $this->request;
        $customer_id = (integer) $customer_id;
        $customer    = OaCustomers::findFirst('customer_id=' . $customer_id);

        if (! $customer) {
            return $this->forward('error/modal', array('message' => 'The record not found'));
        }

        if ($request->isPost()) {
            $follow = new OaCustomerFollowLogs;
            $follow->customer_id = $customer_id;

            // 获取上传结果
            if ($request->hasFiles()) {
                $key = 'screenshot';
                $uploader = get_uploader($key, array(
                    'path'      => config('upload.basePath') . '/follow',
                    'types'     => array('image/jpeg', 'image/gif', 'image/bmp','image/png'),
                    'maxSize'   => config('upload.maxSize'),
                    'rename'    => new Formax\Uploader\Rename\Date,
                ));

                if ($uploader->getErrno($key) !== UPLOAD_ERR_OK) {
                    return $this->ajax->error($uploader->getErrorMessage($key));
                }
                $follow->screenshot = $uploader->getResult($key)->getStaticPath();
            }

            foreach ($request->getPost() as $key => $value) {
                if (isset($follow->$key)) {
                    $follow->$key = $value;
                }
            }

            if (! $follow->create()) {
                return $this->ajax->error(__($follow->getMessage()));
            }

            // 更新跟进时间
            $customer->last_followed = time();
            $customer->update();

            return $this->ajax->success(__('Follow-up record added succeed'));
        }

        $this->view->customer  = $customer;
        $this->view->types     = OaCustomerTypes::getAll();
    }

}
